const {
  mysql
} = require('../qcloud');

const {
  mysqlQuery
} = require('../tools/utils');

module.exports = async ctx => {
  let query = ctx.request.query;
  if (ctx.request.query.type == 'sort') {
    let sql = `SELECT
	*
FROM
	music AS a
WHERE
	(
		SELECT
			COUNT(*)
		FROM
			music AS b
		WHERE
			b.type = a.type
		AND b.id >= a.id
		ORDER BY
			counter DESC
	) <= 20
ORDER BY
	a.type ASC,
  a.counter DESC`;
    let list = await mysqlQuery(sql);
    // console.log(list);
    ctx.state.data = {
      list
    }
  }
  if (query.lang) {
    // console.log(query)
    let pageIndex = query.pageIndex;
    let lang = query.lang;
    let size = 20;
    let list = await mysql('music')
      .select('*')
      .where('type', lang)
      .orderBy('create_time', 'desc')
      .limit(size)
      .offset(Number(pageIndex) * size)
    ctx.state.data = {
      list
    }

  } else {
    let list = await mysql('music')
      .select('*')
      .orderBy('counter', 'desc')
      .limit(20)
    ctx.state.data = {
      list
    }
  }
}
